package fr.utt.lo02.CrazyEights.view;


import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JLabel;
import javax.swing.JPanel;

import fr.utt.lo02.CrazyEights.model.Game;
import fr.utt.lo02.CrazyEights.model.piles.StockPile;
import fr.utt.lo02.CrazyEights.model.players.Human;


/**
 * A panel which represents a stockPile
 * @author Jeremy
 *
 */
public class StockPilePanel extends JPanel implements Observer{
	private static final long serialVersionUID = 1L;
	private StockPile stockPile;
	private ImageLabel imageLabel;
	private JLabel nbCardsInPile;
	
	/**
	 * Create the panel for the given stockPile
	 * @param sp the stockpile for which we create the panel
	 */
	public StockPilePanel(StockPile sp){
		stockPile = sp;
		sp.addObserver(this);
		Game.getInstance().getPlayersList().addObserver(this);
		nbCardsInPile = new JLabel();
		nbCardsInPile.setForeground(Color.white);
		updateStockPile();
	}
	
	/**
	 * Refresh the display of the stockPile
	 */
	public void updateStockPile(){
		this.setVisible(false);
		this.removeAll();
		this.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.gridy = 0;
		if(!stockPile.isEmpty()){
			imageLabel = new ImageLabel();
			this.imageLabel.setPreferredSize(new Dimension(MainWindow.cardWidth, MainWindow.cardHeight));
			this.add(imageLabel);
			if(Game.getInstance().getPlayersList().getCurrentPlayer() instanceof Human){
				imageLabel.addMouseListener(new CardState());
			}
		}
		nbCardsInPile.setText(stockPile.getNbCardsInPile()+ " remaining cards");
		c.gridy = 1;
		this.add(nbCardsInPile,c);
		this.setVisible(true);
	}
	
	public void update(Observable o, Object arg){
		updateStockPile();
	}
	
	/**
	 * MouseAdapter for to know if the StockPile was clicked
	 * @author Jeremy
	 *
	 */
	class CardState extends MouseAdapter{
		
		public CardState(){
		}
		
		public void mouseClicked(MouseEvent e){
			Game.getInstance().getPlayersList().getCurrentPlayer().play(null);
		}
	}
}
